﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.Data.Sqlite;
using YougeBookmark.Models;
using YougeBookmark.Services;

namespace YougeBookmark.Views
{
    /// <summary>
    /// 标签管理窗体（实现标签的增删改查）
    /// </summary>
    public partial class TagManagerForm : Form
    {
        private readonly DatabaseService _dbService;
        private List<Tag> _tags = new List<Tag>();
        private DataGridView dgvTags;
        private Button btnAdd;
        private Button btnEdit;
        private Button btnDelete;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
        private Button btnSave;

        public TagManagerForm(DatabaseService dbService)
        {
            _dbService = dbService;
            InitializeComponent();
            Load += TagManagerForm_Load;
        }

        /// <summary>
        /// 初始化窗体控件
        /// </summary>
        private void InitializeComponent()
        {
            dgvTags = new DataGridView();
            btnAdd = new Button();
            btnEdit = new Button();
            btnDelete = new Button();
            btnSave = new Button();
            dataGridViewTextBoxColumn1 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn2 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn3 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn4 = new DataGridViewTextBoxColumn();
            ((System.ComponentModel.ISupportInitialize)dgvTags).BeginInit();
            SuspendLayout();
            // 
            // dgvTags
            // 
            dgvTags.Columns.AddRange(new DataGridViewColumn[] { dataGridViewTextBoxColumn1, dataGridViewTextBoxColumn2, dataGridViewTextBoxColumn3, dataGridViewTextBoxColumn4 });
            dgvTags.Location = new Point(0, 0);
            dgvTags.Name = "dgvTags";
            dgvTags.Size = new Size(507, 150);
            dgvTags.TabIndex = 0;
            // 
            // btnAdd
            // 
            btnAdd.Location = new Point(0, 0);
            btnAdd.Name = "btnAdd";
            btnAdd.Size = new Size(75, 23);
            btnAdd.TabIndex = 1;
            btnAdd.Click += BtnAdd_Click;
            // 
            // btnEdit
            // 
            btnEdit.Location = new Point(0, 0);
            btnEdit.Name = "btnEdit";
            btnEdit.Size = new Size(75, 23);
            btnEdit.TabIndex = 2;
            btnEdit.Click += BtnEdit_Click;
            // 
            // btnDelete
            // 
            btnDelete.Location = new Point(0, 0);
            btnDelete.Name = "btnDelete";
            btnDelete.Size = new Size(75, 23);
            btnDelete.TabIndex = 3;
            btnDelete.Click += BtnDelete_Click;
            // 
            // btnSave
            // 
            btnSave.Location = new Point(0, 0);
            btnSave.Name = "btnSave";
            btnSave.Size = new Size(75, 23);
            btnSave.TabIndex = 4;
            btnSave.Click += BtnSave_Click;
            // 
            // dataGridViewTextBoxColumn1
            // 
            dataGridViewTextBoxColumn1.HeaderText = "ID";
            dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
            // 
            // dataGridViewTextBoxColumn2
            // 
            dataGridViewTextBoxColumn2.HeaderText = "标签名称";
            dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
            // 
            // dataGridViewTextBoxColumn3
            // 
            dataGridViewTextBoxColumn3.HeaderText = "备注说明";
            dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
            // 
            // dataGridViewTextBoxColumn4
            // 
            dataGridViewTextBoxColumn4.HeaderText = "创建时间";
            dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
            // 
            // TagManagerForm
            // 
            ClientSize = new Size(584, 361);
            Controls.Add(dgvTags);
            Controls.Add(btnAdd);
            Controls.Add(btnEdit);
            Controls.Add(btnDelete);
            Controls.Add(btnSave);
            Name = "TagManagerForm";
            StartPosition = FormStartPosition.CenterParent;
            Text = "标签管理";
            ((System.ComponentModel.ISupportInitialize)dgvTags).EndInit();
            ResumeLayout(false);
        }

        /// <summary>
        /// 窗体加载时初始化数据
        /// </summary>
        private async void TagManagerForm_Load(object sender, EventArgs e)
        {
            try
            {
                _tags = await _dbService.GetAllTagsAsync();
                RefreshGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载标签失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 刷新数据表格
        /// </summary>
        private void RefreshGrid()
        {
            dgvTags.Rows.Clear();
            foreach (var tag in _tags)
            {
                dgvTags.Rows.Add(
                    tag.Id,
                    tag.Name,
                    tag.Description,
                    tag.CreatedTime.ToLocalTime()
                );
            }
        }

        /// <summary>
        /// 新增标签按钮点击事件
        /// </summary>
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            using var inputForm = new InputDialog("新增标签");
            if (inputForm.ShowDialog() == DialogResult.OK)
            {
                var newTag = new Tag
                {
                    Name = inputForm.Value,
                    Description = inputForm.Description
                };
                _tags.Add(newTag);
                RefreshGrid();
            }
        }

        /// <summary>
        /// 编辑标签按钮点击事件
        /// </summary>
        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (dgvTags.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要编辑的标签");
                return;
            }

            var selectedId = (int)dgvTags.SelectedRows[0].Cells["Id"].Value;
            var tag = _tags.Find(t => t.Id == selectedId);

            using var inputForm = new InputDialog("编辑标签", tag.Name, tag.Description);
            if (inputForm.ShowDialog() == DialogResult.OK)
            {
                tag.Name = inputForm.Value;
                tag.Description = inputForm.Description;
                RefreshGrid();
            }
        }

        /// <summary>
        /// 删除标签按钮点击事件
        /// </summary>
        private async void BtnDelete_Click(object sender, EventArgs e)
        {
            if (dgvTags.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的标签");
                return;
            }

            if (MessageBox.Show("确定删除该标签？", "警告",
                MessageBoxButtons.YesNo) != DialogResult.Yes) return;

            var selectedId = (int)dgvTags.SelectedRows[0].Cells["Id"].Value;
            var tag = _tags.Find(t => t.Id == selectedId);

            try
            {
                // 从数据库删除
                await _dbService.ExecuteSqlAsync(
                    "DELETE FROM Tags WHERE Id = @id",
                    new SqliteParameter("@id", selectedId));

                // 从内存列表移除
                _tags.Remove(tag);
                RefreshGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 批量保存按钮点击事件
        /// </summary>
        private async void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (var tag in _tags)
                {
                    // 新增标签没有ID
                    if (tag.Id == 0)
                    {
                        await _dbService.ExecuteSqlAsync(
                            "INSERT INTO Tags (Name, Description) VALUES (@name, @desc)",
                            new SqliteParameter("@name", tag.Name),
                            new SqliteParameter("@desc", tag.Description ?? (object)DBNull.Value));
                    }
                    else // 更新已有标签
                    {
                        await _dbService.ExecuteSqlAsync(
                            "UPDATE Tags SET Name = @name, Description = @desc WHERE Id = @id",
                            new SqliteParameter("@name", tag.Name),
                            new SqliteParameter("@desc", tag.Description ?? (object)DBNull.Value),
                            new SqliteParameter("@id", tag.Id));
                    }
                }

                MessageBox.Show("保存成功");
                DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 输入对话框（内部类）
        /// </summary>
        private class InputDialog : Form
        {
            public string Value { get; private set; }
            public string Description { get; private set; }

            public InputDialog(string title, string defaultValue = "", string defaultDesc = "")
            {
                Text = title;
                Size = new Size(300, 200);
                StartPosition = FormStartPosition.CenterParent;

                var lblName = new Label { Text = "名称:", Location = new Point(20, 20) };
                var txtName = new TextBox { Location = new Point(80, 20), Width = 180, Text = defaultValue };

                var lblDesc = new Label { Text = "说明:", Location = new Point(20, 60) };
                var txtDesc = new TextBox
                {
                    Location = new Point(80, 60),
                    Width = 180,
                    Height = 80,
                    Multiline = true,
                    Text = defaultDesc
                };

                var btnOk = new Button { Text = "确定", DialogResult = DialogResult.OK, Location = new Point(120, 150) };
                btnOk.Click += (s, e) =>
                {
                    if (string.IsNullOrWhiteSpace(txtName.Text))
                    {
                        MessageBox.Show("名称不能为空");
                        return;
                    }
                    Value = txtName.Text.Trim();
                    Description = txtDesc.Text.Trim();
                };

                Controls.AddRange(new Control[] { lblName, txtName, lblDesc, txtDesc, btnOk });
            }
        }
    }
}